﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Text;
using Microsoft.Extensions.DependencyInjection;

namespace ME860.DotNetty.Common
{
    public static class ApplicationService
    {
        private static IServiceCollection Services;
        private static IServiceProvider ServiceProvider;
        /// <summary>
        /// 注册服务
        /// </summary>
        /// <param name="actions"></param>
        public static void RegistorServices(params Action<IServiceCollection>[] actions)
        {
            Services = new ServiceCollection();
            foreach (var action in actions)
            {
                action.Invoke(Services);
            }
        }
        /// <summary>
        /// 构建服务
        /// </summary>
        public static void BuildServices()
        {
            if(Services==null) throw new DotNettyServerException("服务未注册，请先调用RegistorServices方法");
            ServiceProvider = Services.BuildServiceProvider();
        }

        /// <summary>
        /// 获取一个服务
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static object GetService(Type type)
        {
            return ServiceProvider.GetService(type);
        }
        /// <summary>
        /// 获取一个服务泛型
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T GetService<T>()
        {
            return ServiceProvider.GetService<T>();
        }
    }
}
